import axios from "axios";
import { Toast } from "vant";

import crypto from "crypto";
import qs from "qs"; // 根据需求是否导入qs模块
// 固定参数携带
const times = new Date().getTime();
const md5 = crypto.createHash("md5");
md5.update(times + "35e5c1b47ce3");

let sign = md5.digest("hex")
let timestamp = times
let params = {
  sign,
  timestamp
};

// 创建文件上传axios
var fileAjax = axios.create({
  baseURL: process.env.VUE_APP_API + process.env.VUE_APP_PUBLIC_PATH,
  timeout: 20000,
  headers: { 'Content-Type': 'multipart/form-data' },
  transformRequest: [function (data) {
    // 创建form对象
    var formData = new FormData()
    for (const keys in data) {
      if (data.hasOwnProperty(keys)) {
        const el = data[keys];
        formData.append(keys, el)
      }
    }

    formData.append('sign', sign)
    formData.append('timestamp', timestamp)

    return formData
  }]
});

Vue.prototype.fileAjax = fileAjax

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
      },
      transformRequest: [function (data) {
        data = qs.stringify({ ...data, ...params })
        return data;
      }],
    };

    return config;
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        // if (!Object.keys(this.queue).length) {
        // }
        this.queue[url] = true;
        // console.log(config, "----------config--------");
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        console.log(res, "----------res--------");
        const { data, status, message } = res;
        if (status === 200) {
          data.status = parseInt(data.status)

          if (data.status === 200) {
            return data;
          } else {
            Toast(data.message);
          }

        } else {
          Toast(message);
        }
        // return { data, status };
      },
      error => {
        Toast("服务连接失败，请刷新重试")
        return Promise.reject(error);
      }
    );
  }
  request(options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options, {
      // 'withCredentials' 请求超时时间
      timeout: 30000,
      // 'withCredentials' 表示跨域请求时是否需要使用凭证
      withCredentials: false
    });
    this.interceptors(instance, options.url);
    return instance(options);
  }
}
export default HttpRequest;
